<?php 

namespace App\Http\Controllers;

use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Http\Request;
use App\Http\model\Sms;
use App\Http\model\order;
use App\Http\model\Curdpost;
use Illuminate\Support\Facades\DB;

class OrderController extends BaseController
{
    /**
     * [等待司机接单时展示信息api]
     * @Author   孙丽男
     * @DateTime 2018-05-24
     * @version  0.8
     * @param    [订单ID] [int] orderId
     * @return   [json] $result
     */
    public function waitReceipt(Request $request){

        $result = array();

        $orderId = $request['orderId'];
        if (!$orderId) {
            
            $result['code'] = 1002;
            $result['msg'] = '参数为空';
            return json_encode($result);

        }
        
        //需查询字段
        $fields = array(
            'order.id',
            'order.implementstatus',
            'order.end',
            'order.original',
            'order.originaldegree',
            'order.enddegree',
            'order.usetime',
            'order.sumpeople',
            'order.orderstatus',
            'order.createtime',
            'order_extend.passenger_name',
            'order_extend.passenger_phone',
            'car_series.name as seriesname'
        );

        $orderModel = new order;

        return $orderModel->waitReceiptModel($fields,$orderId);
    }

    /**
     * [订单进行中api]
     * @Author   孙丽男
     * @DateTime 2018-05-24
     * @param    [订单ID] [int] orderId
     * @version  0.8
     * @return   [json]  $result
     */
    public function orderProcess(Request $request){
        
        $result = array();

        $orderId = $request['orderId'];
        if (!$orderId) {
            
            $result['code'] = 1002;
            $result['msg'] = '参数为空';
            return json_encode($result);

        }

        //需查询字段
        $fields = array(
            'order.id',
            'order.end',
            'order.original',
            'order.originaldegree',
            'order.enddegree',
            'order.orderstatus',
            'driver.driver_name as drivername',
            'driver.driver_phone as driverphone',
            'driver.user_pic',
            'car_series.name as seriesname',
            'car_car.num as carnumber',
            'car_car.color',
            'order.implementstatus',
        );
        $orderModel = new order;
        
        $orderres = $orderModel->orderProcessModel($fields,$orderId);

        if ($orderres['code'] == 1000) {
        	// print_r($orderres);die;
            $data = $this->driverPosition($orderres['data']['driverphone']);
            if ($data) {
                $orderres['data']['Latitude'] = (string)$data['Latitude'];
                $orderres['data']['Longitude'] = (string)$data['Longitude'];
                $result['msg'] = '查询成功';
                $result['code'] = 1000;
                $result['data'] = $orderres;
            }else{
                $result['msg'] = '获取司机位置失败';
                $result['code'] = 1004;
            }
            return json_encode($result);
        }else{
            return json_encode($orderres);
        }
    }

    /**
     * [服务结束/待支付api]
     * @Author   孙丽男
     * @DateTime 2018-05-24
     * @param    [订单ID] [int] orderId
     * @version  0.8
     * @return   [json]   $result
     */
    public function serverEnd(Request $request){

        $result = array();

        $orderId = $request['orderId'];
        if (!$orderId) {
            
            $result['code'] = 1002;
            $result['msg'] = '参数为空';
            return json_encode($result);

        }

        //需查询字段
        $fields = array(
            'order.id',
            'order.end',
            'order.original',
            'order.originaldegree',
            'order.enddegree',
            'order.orderstatus',
            'order.num as ordernum',
            'driver.driver_name as drivername',
            'driver.driver_phone as driverphone',
            'driver.user_pic',
            'car_series.name as seriesname',
            'car_car.num as carnumber',
            'car_car.color',
            'order.implementstatus',
            'order_price.preprice',
            'order_price.endprice',
            'order_price.difprice',
        );
        $orderModel = new order;

        return $orderModel->serverEndModel($fields,$orderId);
        
    }

    /**
     * [取消订单api]
     * @Author   孙丽男
     * @DateTime 2018-05-24
     * @param    [订单ID] [int] orderid
     * @version  0.8
     * @return   [json]     $result
     */
    public function cancelOrder(Request $request){

        $result = array();

        $orderId = $request['orderId'];
        if (!$orderId) {
            
            $result['code'] = 1002;
            $result['msg'] = '参数为空';
            return json_encode($result);

        }
        $this->syncData($orderId);
        //需查询字段
        $fields = array(
            'order.id',
            'order.uid',
            'order.usetime',
            'order.orderstatus',
            'order_price.preprice',
            'server_item.name as itemname',
            'social_user.phone',
            'social_user.sum_money'
        );
        $orderModel = new order;

        $orderInfoArr = $orderModel->orderInfo($fields,$orderId);

        if ($orderInfoArr['code'] == 1004) {
            
            return json_encode($orderInfoArr);
        }   
        date_default_timezone_set('PRC');

        //当前时间
        $datetime = strtotime(date('Y-m-d H:i:s'));
        //预约时间
        $appointment = $orderInfoArr['data']['usetime'];
        //时间差/小时
        $diftime = round(($appointment - $datetime)/3600,2);
        
        $uid = $orderInfoArr['data']['uid'];
        $price = $orderInfoArr['data']['preprice'];
        $sum_money = $orderInfoArr['data']['sum_money'];
        $type = $orderInfoArr['data']['itemname'];
        $phone = $orderInfoArr['data']['phone'];
        $percentage = '';

        /**
         * 判断时间差，根据时间差扣款，大于两小时不扣款，
         * 小于等于两小时并且大于一小时扣预付款80%，小于等于一小时扣50%，预约订单开始之后扣去全部预约款
         */ 
        if ( $diftime > 2 ) {
            
            //差值
            $difprice = $price ;
            $percentage = 0;
        }elseif ($diftime <= 2 && $diftime > 1) {
            
            $difprice = $price - $price*0.5;
            $percentage = 50;

        }elseif($diftime < 1 && $diftime > 0){

            $difprice = $price - $price*0.8;
            $percentage = 80;

        }else{

            $res = $orderModel->updateStatusModel($orderId);

            if ($res['code'] == 1000) {
                //扣除全部预付款，直接发送订单取消成功短信
                $percentage = 100;
                $sendResult = $this->cancelSms($percentage,$appointment,$phone,$type);

                if ($sendResult == 1000) {
                    
                    $code = $this->syncData($orderId);
                    if ($code == 1009) {
                        $result['code'] = 1011;
                        $result['msg'] = '获取位置信息错误';
                    }elseif ($code == 1010) {
                        $result['code'] = 1010;
                        $result['msg'] = '同步失败';
                    }else{
                        $result['code'] = 1000;
                        $result['msg'] = '取消成功';
                    }
                    return json_encode($result);
                }else{

                    $result['code'] = 1005;
                    $result['msg'] = '短信发送失败';
                    return json_encode($result);
                }
            }else{
                return json_encode($res);
            }

        }
    
        //将扣除之后的预付款返还给用户并修改订单状态
        $money = $sum_money + $difprice ;

        $updateResult = $orderModel->updateModel($money,$uid,$orderId);
        
        if ($updateResult['code'] == 1000) {
            
            $sendResult = $this->cancelSms($percentage,$appointment,$phone,$type);
            
            if ($sendResult == 1000) {

                $code = $this->syncData($orderId);
                if ($code == 1009) {
                    $result['code'] = 1009;
                    $result['msg'] = '获取位置信息错误';
                }elseif ($code == 1010) {
                    $result['code'] = 1010;
                    $result['msg'] = '同步失败';
                }else{
                    $result['code'] = 1000;
                    $result['msg'] = '取消成功';
                }
                return json_encode($result);

            }else{

                $result['code'] = 1005;
                $result['msg'] = '短信发送失败';
                return json_encode($result);
            }

        }else{

            return json_encode($updateResult);
        }

    }

    /**
     * [orderList 订单列表]
     * @Author   孙丽男
     * @DateTime 2018-06-14
     * @param    [type]
     * @version  6.2
     * @return   [type]     [description]
     */
    public function orderList(Request $request){

        $result = array();

        $type = $request['type'];
        $uid = $request->get('id');
        // $page = $request['page'];
        // $limit = $request['limit'];
        if (!$type || !$uid ) {
            
            $result['code'] = 1002;
            $result['msg'] = '参数为空';
            return json_encode($result);

        }
        $where['uid'] = $uid;
        $where['server_item.name'] = $type;
        // $off = ($page-1)*$limit;
         $re = Db::table('order')
          ->leftJoin('server_item','order.typeid','=','server_item.id')
          ->where($where)
          // ->orderBy('order.orderstatus','asc')
          ->orderBy('order.createtime','desc')
          ->select('order.id','order.usetime','order.original','order.end','order.originaldegree','order.enddegree','order.status','server_item.name','order.orderstatus','order.implementstatus','order.orderstatus')
          // ->offset($off)
          // ->limit($limit)
          ->get();
       $re = json_decode(json_encode($re),true);
       $arr = [];
       if(!empty($re)){
          foreach ($re as $key => &$value) {
              $value['usetime'] = date('Y-m-d H:i',$value['usetime']);
              if($value['orderstatus'] == 5){
                $value['statusName'] = '已取消';
                $arr['已取消订单'][] = $value;//已取消订单
              }elseif($value['orderstatus'] == 3){
                $value['statusName'] = '进行中';
                $arr['进行中订单'][] = $value;//进行中订单
              }elseif($value['orderstatus'] ==4){
                $value['statusName'] = '已完成';
                $arr['已完成订单'][] = $value;//已完成订单
              }else{
                $value['statusName'] = '未开始';
                $arr['未开始订单'][] = $value;//未开始订单
              }

          }
          $retuen['code'] = 1000;
          $retuen['data'] = $arr;
          $retuen['msg'] = '请求成功';
       }else{
          $retuen['code'] = 1004;
            $retuen['msg'] = '请求失败';
       }
 
        return json_encode($retuen);
    }

    /**
     * [取消订单成功发送短信api]
     * @Author   孙丽男
     * @DateTime 2018-05-24
     * @param    [订单ID] [int] orderid
     * @version  0.8
     * @return   [json]     $result
     */
    protected function cancelSms($percentage,$appointment,$phone,$type){

        $date = date('Y-m-d H:i:s',$appointment);
        $adress = 'https://b.shidaichuxing.com/api/setorder/orderlist';

        $msg = '您预订'.$date.'的'.$type.'订单已取消，本次取消扣除预估费用'.$percentage.'%。查看详情请点击'.$adress.'或搜索下载APP时代出行，感谢您的使用！【时代出行】';
        
        $code = new Sms();
        $re = $code -> sendSMS($phone,$msg); 
        $data = json_decode($re,true);
  		// print_r($data);die;
        if($data['error'] == 0){
            return 1000;
        }else{
            return 1005;
        }

    }

    /**
     * [driverPosition 司机实时位置（百度鹰眼）]
     * @Author   孙丽男
     * @DateTime 2018-06-19
     * @param    [type]
     * @version  6.2
     * @param    [type]     $value [description]
     * @return   [type]            [description]
     */
    private function driverPosition($value)
    {
        $ak = 'RGwhFRkSZfva32BN96csoObm4FIfiCAY';
        $serid = 158008;
        $url = 'http://yingyan.baidu.com/api/v3/track/getlatestpoint?ak='.$ak.'&service_id='.$serid.'&entity_name='.$value;
        $re = $this->get_curl_json($url);
        // $re = json_decode($re,true);
        $data = array();
        if($re['status'] == 0){

            $data['Latitude'] = $re['latest_point']['latitude'];
            $data['Longitude'] = $re['latest_point']['longitude'];
            $data['Direction'] = $re['latest_point']['direction'];
            if (isset($re['latest_point']['height'])) {
            	$data['Elevation'] = $re['latest_point']['height'];
            }else{
            	$data['Elevation'] = 0;
            }
            $data['Speed'] = $re['latest_point']['speed'];
            return $data;
        }else{
            return false;
        }
        
    }

    /**
     * [syncData 数据同步]
     * @Author   孙丽男
     * @DateTime 2018-06-19
     * @param    [type]
     * @version  6.2
     * @return   [type]     [description]
     */
    private function syncData($orderId){

        //查询同步数据
        $fields = array(
                'order.num',
                'order.createtime',
                'order.implementstatus',
                'driver.driver_phone',
                'driver.licenseId',
                'driver.attendant',
                'car_car.num as carnum',
                'car_car.mileage'
            );
        $orderModel = new order;

        $find = $orderModel->findSync($orderId,$fields);
// dump($find['createtime']);die;
        $curd = new Curdpost;

        //更新取消订单表
        $cancel['CompanyId'] = '';
        $cancel['Address'] = 110100;
        $cancel['OrderId'] = $find['num'];
        $cancel['OrderTime'] = date('ymdhis',strtotime($find['createtime']));
        $cancel['CancelTime'] = date('ymdhis',time());
        $cancel['Operator'] = 1;
        if ($find['implementstatus'] >= 5) {
            $cancel['CancelTypeCode'] = 4;
        }else{
            $cancel['CancelTypeCode'] = 1;
        }
        $cancel['CancelReason'] = '';
        $resCancel = $curd->NewInsert('ordercancel',$cancel);

        //获取位置信息
        $data = $this->driverPosition($find['driver_phone']);

        if ($data) {

            $data['PositionTime'] = time();
            $data['CompanyId'] = '';
            $data['VehicleNo'] = $find['carnum'];
            $data['BizStatus'] = $find['attendant'];
            $data['OrderId'] = $find['num'];
            $where = "OrderId=".$find['num'];
            //更新司机定位表
            $driver = $data;
            $driver['LicenseId'] = $find['licenseId'];
            $driver['DriverRegionCode'] = 110100;
            $driver['Enerypt'] = 3;
            //更新车辆定位表
            $car = $data;
            $car['Mileage'] = $find['mileage'];
            $car['Encrypt'] = 3;
            $car['WarnStatus'] = '';
            $car['VehStatus'] = '';
            $car['VehicleRegionCode'] = 110100;

            //查询是否定位表中是否有该订单号，司机与车辆分别判断
            /**
             * 查询代码
             */
            $findDriver = $curd->selectArr('positiondriver',$where);;
            if ($findDriver['code'] == 1) {

                $resDriver = $curd->NewUpdate('positiondriver',$driver,$where);

            }else{

                $resDriver = $curd->NewInsert('positiondriver',$driver);
            }

            /**
             * 查询车辆表代码
             */
            $findCar = $curd->selectArr('positionvehicle',$where);
            if ($findCar['code'] == 1000) {

                $resCar = $curd->NewUpdate('positionvehicle',$car,$where);
            }else{

                $resCar = $curd->NewInsert('positionvehicle',$car);
            }

            if ($resDriver && $resCar && $resCancel) {
                
                return 1000;
            }else{
                return 1010;
            }

        }else{
            return 1009;
        }
    }

    /**
     * 模拟get请求
     * @param $url
     * @return mixed
     */
    private function get_curl_json($url){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
        $result = curl_exec($ch);
        if(curl_errno($ch)){
            print_r(curl_error($ch));
        }
        curl_close($ch);
        return json_decode($result,TRUE);
    }
}